package com.doubao.server;

import com.doubao.config.AppConfig;
import com.doubao.nettyhandler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * description:Nettyserver
 * <p>
 * author:sult
 * time: 2018/11/1 13:08
 **/
@Service
public class NettyServer {

    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

    public void start(){
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workGroup);
                b.channel(NioServerSocketChannel.class);
                b.childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel e) {
                        e.pipeline().addLast("http-codec", new HttpServerCodec());
                        e.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
                        e.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        e.pipeline().addLast("handler", new WebSocketHandler());
                    }
                });
                log.info("服务端开启等待客户端连接....端口号:"+AppConfig.PORT);
                Channel ch = b.bind(AppConfig.PORT).sync().channel();
                ch.closeFuture().sync();

            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                //优雅的退出程序
                bossGroup.shutdownGracefully();
                workGroup.shutdownGracefully();
            }
    }
}
